package com.Akronmcp.hm;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import com.Akronmcp.hta.obj.HCondition;
import com.Akronmcp.hta.obj.HPar;
import com.Akronmcp.hta.obj.HPar2;
import com.Akronmcp.hta.obj.HopChat;
import com.Akronmcp.hta.obj.HopHolo;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**HopMess公告线程类*/
public class HopMess {

	boolean enable = false;
    //是否开启


	boolean random = false;
	//是否随机发送
	
	String id;
	//id
	
	int interval = 600;
	//发送间隔
	
	BukkitTask thread;
	//线程
	
	public final static Map<String,HopMess> hmMap = new HashMap<String,HopMess>();
	//储存各个公告线程的列表
	
	List<HPar> hl = new ArrayList<HPar>();
	//公告线程的公告列表
	
	
	Date d1;
	Date d2;
	//日期区间
	
	/**设置日期区间*/
	public void setDate(Date d1,Date d2)
	{
		this.d1=d1;
		this.d2=d2;
	}
	
	public Date getBeginDate()
	{
		return d1;
	}
	
	public Date getEndDate()
	{
		return d2;
	}
	
	
	Calendar c1;
	Calendar c2;
	//每日定时开始结束时间(只设定小时,分钟),如18:30-20:00
	
	public Calendar getDayBeginDate()
	{
		return c1;
	}
	
	public Calendar getDayEndDate()
	{
		return c2;
	}
	
	public void setDaily(Calendar begin,Calendar end)
	{
		c1=begin;
		c2=end;
	}
	
	
	List<HCondition> cl = new ArrayList<HCondition>();
    //发送玩家需求条件
    
	List<HCondition> obcl = new ArrayList<HCondition>();
	//发送玩家的不能需求的条件
	
    public List<HCondition> getConditions() {
		return cl;
	}
    /**设置需求条件*/
	public void setConditions(List<HCondition> cl) {
		this.cl = cl;
	}
	/**筛选不符合条件的玩家*/
	public List<Player> checkObCondition(List<Player> pl)
	{		
		if(!obcl.isEmpty())
		for(HCondition hc:obcl)
		{
			pl = hc.obFilt(pl);
		}
		
		return pl;
		
	}

   public List<HCondition> getObConditions() {
		return obcl;
	}
   /**设置不需求条件*/
	public void setObConditions(List<HCondition> cl) {
		this.obcl = cl;
	}
	/**筛选符合条件的玩家*/
	public List<Player> checkCondition(List<Player> pl)
	{		
		if(!cl.isEmpty())
		for(HCondition hc:cl)
		{
			pl = hc.Filt(pl);
		}
		
		return pl;
		
	}
	
	
	boolean web = false;
	//是否开启网络模式
	
	String url;
	//url地址
	
	String listname;	
	//json列表名
	
	Map<String,String> webargs;
	//网络get参数
	
	String webtext = "{content}";
	//网络的文字模板
	HPar webmodule;
	//网络文本的模板
		
	String module;
	//保存的模板名

	
	/**设置网络参数,并开启网络模式*/
	public void setWeb(String url,String listname,String webtext,HPar webmodule)
	{
		this.url = url;
		this.listname = listname;
		this.webtext = webtext;
		this.webmodule = webmodule;
		
		
       
		
		web = true;
	}
	
	/**设置url参数*/
	public void setWebArgs(Map<String, String> args)
	{
		this.webargs = args;
		
	}
	
	
    public String getModule() {
		return module;
	}

	public void setModule(String module) {
		this.module = module;
	}

	

	
	public HopMess()
	{
		
	}
	
	/**开启循环发送*/
	public void goStart()
	{
		
		//定时线程
		thread = new BukkitRunnable() 
		{
			int index = 0;
			//集合内索引
			
			boolean firstgetweb = true;
			
			public void run() 
			{
				if(!enable)
				{
					cancel();
					return;
				}
				//开关
				
				if(firstgetweb&&web)
				{//若开启网络模式,则首次获取
					getFromWeb();
					firstgetweb = false;
				}
				
				if(random)
				{//若随机,则随机处理索引
					Random ra = new Random();
					index = ra.nextInt(hl.size());
				}
				
				List<Player> pl = new ArrayList<Player>(Bukkit.getOnlinePlayers());
			
				pl = checkCondition(pl);
				final List<Player> pl0 = checkObCondition(pl);
				//筛选玩家
					
				for(HPar htx:hl)
				{
					if(htx instanceof HopHolo)
					{
						HopHolo holo = (HopHolo)htx;
						holo.delete();
					}
				}
				
				if(!hl.isEmpty())
				{
					new BukkitRunnable() {
						@Override
						public void run() {
							
							HPar hml = hl.get(index);
							
							if(hml instanceof HopHolo)
							{
								((HopHolo) hml).create();
							}else
						    hml.send(pl0);
							//发送
						}
					}.runTask(HmM.ins);
				}
				
				if(index+1==hl.size())
				{//索引自增或归零
					index = 0;
					
					if(web)
					{//网络获取
						getFromWeb();
					}
					
				}else
				{
					index++;
				}
	
			}
			
			public synchronized void cancel()
			{
				for(HPar htx:hl)
				{
					if(htx instanceof HopHolo)
					{
						HopHolo holo = (HopHolo)htx;
						holo.delete();
					}
				}
				super.cancel();
			}
			
		}.runTaskTimerAsynchronously(HmM.ins,20L,interval);
		
	}
	
	
	/**从网络获取*/
	private void getFromWeb()
	{
				
		hl.clear();
		//清空公告集合
		
		
		 String httpUrl = url + "?";
			
	  	 for(String k:webargs.keySet())
		 {//输入参数
			httpUrl = httpUrl + "&" + k + "=" + webargs.get(k);
		 }
	  	 
	  	 //构造网络url
	  	 
	  	 

		HmWeb hw = new HmWeb(httpUrl);
		
		hw.start();
		
		try 
		{
			hw.join();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
			System.out.println("出错了?");
		}
		
		String result = hw.getResult();
		//输入url,启动网络读取线程,获得结果
		
		
		try 
		{//通过gson分析结果
			
		Gson gson = new Gson();
		JsonObject jo = gson.fromJson(result, JsonObject.class);
		
		JsonArray ja = (JsonArray) jo.get(listname);
		
		for(JsonElement jo2:ja)
		{//遍历句子集合
			String text2 = webtext;
			
			jo2 = jo2.getAsJsonObject();
			
			Set<Entry<String, JsonElement>> es = ((JsonObject) jo2).entrySet();
			
			for(Entry<String, JsonElement> e:es)
			{//遍历jo的节点,分析句子属性
				String k = e.getKey();
				JsonElement v = e.getValue();
	
				text2 = text2.replace("{"+k+"}",v.getAsString());
			}
			
			
			
			HPar hp = (HPar) webmodule.clone();
			hp.setText(text2);
			//克隆模板,设置文本
			
			if(hp instanceof HopChat)
			{//构造hchat
				((HopChat) hp).create();
			}
			
			if(hp instanceof HPar2)
			{//构造hop特效
				((HPar2) hp).setModule(module);
			}
			
			hl.add(hp);

		}
		
		}catch (Exception e) {
			
			e.printStackTrace();
			System.out.println("读取错误,网络实际返回结果"+result);
			
		}
		
		
		
	}
	
	
	/**是否随机发送*/
	public boolean isRandom() {
		return random;
	}

	/**设置是否随机*/
	public void setRandom(boolean random) {
		this.random = random;
	}

	/**添加到全局列表*/
	public void addToMap()
	{
		HopMess.hmMap.put(id, this);
	}
	

	/**是否开启*/
	public boolean isEnable() {
		return enable;
	}


	public String getId() {
		return id;
	}


	public int getInterval() {
		return interval;
	}


	/**获取公告集合*/
	public List<HPar> getHl() {
		return hl;
	}

	/**设置开关条件*/
	public void setEnable(boolean enable) {
		
		if(!enable&&thread!=null)
		{
			thread.cancel();
			thread = null;
		}
		
		this.enable = enable;
		
		
	}

	
	/**设置开始*/
	public void goOn(boolean ifgo)
	{
		
		if(!ifgo&&thread!=null)
		{
			thread.cancel();
			thread = null;
		}
			
		if(ifgo&&enable&&thread==null)
		goStart();
		//防止重复开启线程
	
	}
    
	
	public void setId(String id) {
		this.id = id;
	}

	/**设置发送间隔,单位tick*/
	public void setInterval(int interval) {
		this.interval = interval;
	}

    /**设置公告集合*/
	public void setHl(List<HPar> hl) {
		this.hl = hl;
	}

	/**为公告集合添加项目*/
	public void addObject(HPar hp)
	{
		hl.add(hp);
	}


	
	/**给符合条件的玩家随机发送公告列内的一项*/
	public void send (List<Player> pl)
	{
		
		pl = checkCondition(pl);
		pl = checkObCondition(pl);
		//筛选玩家
		
		if(pl.isEmpty())
		return;
		
		Random ra = new Random();
		int length = hl.size();
		
		hl.get(ra.nextInt(length)).send(pl);
		//发送
	}
	
	/**给符合条件的玩家随机发送公告列内的一项*/
	public void send (Player p)
	{
		List<Player> pl = new ArrayList<Player>();
		pl.add(p);
		
		send(pl);
	}
	
	/**只判断单个玩家的条件对全服发送公告内随机一项*/
	public void sendtoAll(Player p)
	{
		List<Player> pl = new ArrayList<Player>();
		pl.add(p);
		
		pl = checkCondition(pl);
		pl = checkObCondition(pl);
		//筛选玩家
		
		if(!pl.isEmpty())
		{
			Random ra = new Random();
			int length = hl.size();
			hl.get(ra.nextInt(length)).send(new ArrayList<>(Bukkit.getOnlinePlayers()));
		}
		
	}
	
	
}
